package com.yj.forum.services.impl;

import com.yj.forum.common.AppResult;
import com.yj.forum.common.ResultCode;
import com.yj.forum.dao.ArticleMapper;
import com.yj.forum.exception.ApplicationException;
import com.yj.forum.model.Article;
import com.yj.forum.model.Board;
import com.yj.forum.model.User;
import com.yj.forum.services.IArticleService;
import com.yj.forum.services.IBoardService;
import com.yj.forum.services.IUserService;
import com.yj.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    // ⽤⼾和版块的操作
    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private IUserService userService;
    @Resource
    private IBoardService boardService;

    @Override
    public void create(Article article) {
        //非空校验
        if(article == null || article.getBoardId() == null || article.getUserId() == null
        || StringUtil.isEmpty(article.getContent()) || StringUtil.isEmpty(article.getTitle())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 设置默认值
        article.setVisitCount(0); // 访问数
        article.setReplyCount(0); // 回复数
        article.setLikeCount(0); // 点赞数
        article.setDeleteState((byte) 0);
        article.setState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);
        // 写⼊数据库
        int row = articleMapper.insert(article);
        if (row <= 0) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        // 获取⽤⼾信息
        User user = userService.selectById(article.getUserId());
        // 没有找到指定的⽤⼾信息
        if(user == null) {
            log.warn(ResultCode.FAILED_CREATE.toString() + ", 发贴失败, user id = " + article.getUserId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));

        }
        // 更新⽤⼾的发贴数
        userService.addOneArticleCountById(user.getId());

        // 获取板块信息
        Board board = boardService.selectById(article.getBoardId());
        // 没有找到版块的⽤⼾信息
        if(board == null) {
            log.warn(ResultCode.FAILED_CREATE.toString() + ", 发贴失败, board id = " + article.getBoardId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));

        }
        // 更新版块的发贴数
        boardService.addOneArticleCountById(board.getId());

        // 打印⽇志
        log.info(ResultCode.SUCCESS.toString() + ", user id = " +
                article.getUserId() + ", board id = " + article.getBoardId() + ", article id = "+article.getId() + "发帖成功");

    }

    @Override
    public List<Article> selectAll() {
        //调用dao
        List<Article> articles = articleMapper.selectAll();
        return articles;
    }
    /**
     * 根据版块Id 查询所有未被删除的帖子列表
     * @param boardId 版块Id
     * @return 所有未被删除的帖子列表
     */

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        //非空校验
        if(boardId == null || boardId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //检验版块是否存在
        Board board = boardService.selectById(boardId);
        if(board == null) {
            log.warn(ResultCode.FAILED_BOARD_IS_NOT_EXISTS.toString() + " boardId = " + boardId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_IS_NOT_EXISTS));
        }
        //调用dao
        List<Article> articles = articleMapper.selectAllByBoardId(boardId);
        return articles;
    }

    /**
     * 根据版块Id 查询当前文章详情
     * @param id 版块Id
     * @return 当前文章详情
     */
    @Override
    public Article selectDetailById(Long id) {
        //非空校验
        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectDetailById(id);
        //校验
        if(article == null) {
            log.warn(ResultCode.FAILED_ARTICLE_IS_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_IS_NOT_EXISTS));
        }
        //构造对象，数据库更新访问次数
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount() == null ? 1 : article.getVisitCount() + 1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1) {
            // 记录⽇志
            log.warn(ResultCode.ERROR_SERVICES.toString() + "articleId = " + article.getId());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));

        }

        // 对象返回的帖⼦访问数加1
        article.setVisitCount(article.getVisitCount() == null ? 1 : article.getVisitCount() + 1);
        return article;
    }

    /**
     * 根据帖⼦Id更新帖⼦标题与内容
     * @param id 帖⼦Id
     * @param title 标题
     * @param content 内容
     */
    @Override
    public void modify(Long id, String title, String content) {
        //非空校验
        if(id == null || id <= 0 || StringUtil.isEmpty(title) || StringUtil.isEmpty(content)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //构造帖子对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setTitle(title);
        updateArticle.setContent(content);
        updateArticle.setUpdateTime(new Date());
        //调用dao
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        //校验
        if(row != 1) {
            log.error(ResultCode.ERROR_SERVICES.toString()+ ", 受影响的⾏数不等于 1 为 " + row);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

    }

    @Override
    public Article selectById(Long id) {
        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString()+"article id : "+id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return articleMapper.selectByPrimaryKey(id);
    }
    /**
     * 点赞
     * @param id 帖⼦Id
     */
    @Override
    public void thumbsUpById(Long id) {
        //非空校验
        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用dao,拿取文章
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article == null || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_IS_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_IS_NOT_EXISTS));
        }
        //校验文章状态
        if(article.getState() == 1 ) {
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //构造更新数据
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount() == null ? 1 : article.getLikeCount()+1);
        //调用dao 更新数据库
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        //校验结果
        if(row != 1) {
            log.error(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }



    /**
     * 根据Id删除帖⼦
     * @param id 帖⼦Id
    */
    @Override
    public void deleteById(Long id) {
        //非空校验
        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //拿文章
        Article article = articleMapper.selectByPrimaryKey(id);
        //校验
        if(article == null || article.getDeleteState() != 0) {
            log.warn(ResultCode.FAILED_ARTICLE_IS_NOT_EXISTS.toString()+" article id "+id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_IS_NOT_EXISTS));
        }
        if(article.getState() != 0) {

            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString()+" 帖子已封贴 article id "+id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //删除,构造数据
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte)1);
        updateArticle.setState((byte)1);
        //调用dao
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        //校验
        if(row != 1) {
            log.error(ResultCode.ERROR_SERVICES.toString()+ ", 受影响的⾏数不等于 1 为 " + row);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //更新用户与板块
        userService.subOneArticleCountById(article.getUserId());
        boardService.subOneArticleCountById(article.getBoardId());
        log.info("删除帖子成功，article id" + id);
    }
    /**
     * 根据帖⼦Id更新帖⼦回复数
     * @param id 帖⼦Id
     */
    @Override
    public void addOneReplyCountById(Long id) {
        //非空校验
        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //拿文章
        Article article = articleMapper.selectByPrimaryKey(id);
        //校验
        if(article == null || article.getDeleteState() != 0) {
            log.warn(ResultCode.FAILED_ARTICLE_IS_NOT_EXISTS.toString()+" 帖子已封贴 article id "+id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_IS_NOT_EXISTS));
        }
        if( article.getState() != 0) {
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString()+" article id "+id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        // 更新帖⼦回复数
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setReplyCount(article.getReplyCount() == null ? 1 : article.getReplyCount()+1);
        //调用dao
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        //校验
        if(row != 1) {
            log.info("新增帖⼦回复数量失败, userId = " + article.getUserId() + ", articleId = " + article.getId());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

    }
    /**
     * 根据用户Id 查询帖子列表
     * @param userId 用户Id
     * @return 帖子列表
     */
    @Override
    public List<Article> selectByUserId(Long userId) {
        //非空校验
        if(userId == null || userId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //拿用户
        User user = userService.selectById(userId);
        if(user == null || user.getDeleteState() != 0) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString()+" article id "+userId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));

        }
        //调用dao
        List<Article> articles = articleMapper.selectByUserId(userId);
        return articles;
    }
}
